package net.sf.rose.jdbc.factory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;

import org.apache.log4j.Logger;

/**
 * @author fengjian
 * @since 2012/06/23
 */
public class BasicConnectFactory implements ConnectFactory {

	private static Logger logger = Logger.getLogger(BasicConnectFactory.class);

	private String url = null;
	private String user = null;
	private String password = null;
	private String driverClassName = null;

	/**
	 * 设置数据库连接配置文件
	 */
	public void setJDBCFile(String jdbcFile){
		// 加载JDBC配置信息
		InputStream in = BasicConnectFactory.class.getClassLoader().getResourceAsStream(jdbcFile);
		if (in != null) {
			try {
				Properties pro = new Properties();
				pro.load(in);
				in.close();
				url = pro.getProperty("url");
				user = pro.getProperty("username");
				password = pro.getProperty("password");
				driverClassName = pro.getProperty("driverClassName");
				Class.forName(driverClassName);
			} catch (Exception e) {
				String message = "数据库连接初始化失败！";
				logger.error(message, e);
				throw new SystemException(message, SystemErrorCode.DATASOURCE_INITIAL_ERROR);
			}
		} else {
			String message = "数据库连接配置文件查找失败！"+ "没有找到文件：" + jdbcFile + "！";
			logger.error(message);
			throw new SystemException(message, SystemErrorCode.JDBC_FILE_LOAD_ERROR);
		}
	}

	/**
	 * 返回数据库连接
	 */
	@Override
	public Connection getConnection() {
		try {
			Connection con =  DriverManager.getConnection(url, user, password);
			con.setAutoCommit(false);
			return con;
		} catch (SQLException e) {
			String message = "数据库连接创建失败！";
			logger.error(message);
			throw new SystemException(message, SystemErrorCode.CONNECT_CREATE_ERROR);
		}
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
